package com.xwd.web.users;


import com.xwd.domain.Users;
import com.xwd.service.UsersService;
import com.xwd.service.impl.UsersServiceImpl;
import com.xwd.util.PageUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(urlPatterns = "/power/user/users")
public class UserServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if ("select".equals(method)) {
            select(req, resp);
        }else if("add".equals(method)){
            this.addRole(req,resp);
        }

    }

    //查询数据（分页）
    protected void select(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接受参数(分页参数和模糊查参数)
        String index = req.getParameter("index");
        int pageIndex = (index==null||index.length()==0)?1:Integer.parseInt(index);
        //调用service方法
        UsersService service = new UsersServiceImpl();
        PageUtil pageUtil = new PageUtil();
        List<Users> userlist = service.getUserlist(pageIndex, pageUtil.getPageSize());
        pageUtil.setIndex(pageIndex);
        pageUtil.setDataList(userlist);
        int totle = service.getTotle();
        pageUtil.setTotal(totle);
        req.setAttribute("p1",pageUtil);
        req.getRequestDispatcher("list.jsp").forward(req,resp);
    }

    protected void addRole(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        UsersService service = new UsersServiceImpl();
        //获取参数，添加进user对象中
        Users users = new Users();
        users.setLoginName(req.getParameter("loginName"));
        users.setPassWord(req.getParameter("passWord"));
        users.setRealName(req.getParameter("realName"));
        users.setSex(Integer.parseInt(req.getParameter("sex")));
        users.setRoleId(Integer.parseInt(req.getParameter("roleId")));
        users.setEmail(req.getParameter("email"));
        users.setPhone(req.getParameter("phone"));
        users.setAddress(req.getParameter("address"));
        users.setCardId(req.getParameter("cardId"));
        users.setDesc(req.getParameter("desc"));
        //调用方法，存储信息
        int i = service.addUses(users);
        req.setAttribute("users",users);
        PrintWriter writer = resp.getWriter();
        if(i==0){
            writer.print("<script> location.href='/power/role/roles?method=rList'; alert('添加失败，请重试') </script>");
        }
        writer.print("<script> location.href='/power/user/users?method=select'; alert('添加成功！')</script>");
    }
}
